from .models import *
from rest_framework import serializers
import re
from rest_framework.validators import ValidationError
class UserSer(serializers.ModelSerializer):
    password = serializers.CharField(max_length=64,write_only=True,trim_whitespace=True)

    #重写验证方法，添加自己的验证规则
    def validate(self, data):
        username = data.get('username')
        password = data.get('password')
        mobile  = data.get('mobile')
        email = data.get('emial')
        #验证用户名是否满足要求
        if not re.findall(r'^\w{5,20}$',username):
            raise ValidationError("用户名是5到20位数字、字母或下划线")

        #验证密码是否满足要求
        if not re.findall(r'^[\w!@#$%^&*]{8,20}$',password):
            raise ValidationError('密码是8到20位数字、字母或下划线以及特殊!@#$%^&*符号')

        #验证手机号
        if not re.findall(r'^1[34578]\d{9}$',mobile):
            raise ValidationError('手机格式不正确')
        return data

    #重写create方法，实现用户数据的保存
    def create(self, validated_data):
        #保存用户对象
        user = User.objects.create_user(**validated_data)
        #更新密码为哈希加密的
        user.set_password(validated_data.get('password'))
        return user

    class Meta:
        model = User
        fields = ['id','username','password','mobile','email']
        read_only_fields = ['id',]


class PermissionSer(serializers.ModelSerializer):
    type_name = serializers.PrimaryKeyRelatedField(queryset=PermissionType.objects.all())
    typename = serializers.SerializerMethodField(read_only=True)
    def get_typename(self,obj):
        return obj.type_name.name
    class Meta:
        model = Permission
        fields = "__all__"
        read_only_fields = ["id",]

class PermissionTypeSer(serializers.ModelSerializer):
    class Meta:
        model = PermissionType
        fields = "__all__"
        read_only_fields = ['id',]